package com.zzh.sqllib;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.zzh.sqllib.bean.ActionBean;
import com.zzh.sqllib.greendao.gen.ActionBeanDao;
import com.zzh.sqllib.greendao.gen.DaoMaster;
import com.zzh.sqllib.greendao.gen.DaoSession;

import java.util.List;

public class SQL {

    private static final String DB_NAME = "gengyun-db";

    private SQL (){}

    private static class SQLHolder {
        public static final SQL sql = new SQL();
    }

    public static SQL getInstance() {
        return SQLHolder.sql;
    }

    private DaoSession daoSession;

    public void init(Context context){
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
        SQLiteDatabase sqLiteDatabase = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(sqLiteDatabase);
        daoSession = daoMaster.newSession();
    }

    public <T>long inserte (T entity) {
        return this.daoSession.insert(entity);
    }

    public <T>void delete(T entity) {
        this.daoSession.delete(entity);
    }

    public <T>void updata (T entity) {
        this.daoSession.update(entity);
    }

    /**
     * 根据时间戳区间查询数据
     * @param startTime 开始时间戳
     * @param endTime //结束时间戳
     * @return // 返回查询的数据集合
     */
    public List<ActionBean> selectActions (long startTime, long endTime){
        return this.daoSession
                .getActionBeanDao()
                .queryBuilder()
                /*todo between 在不同的数据库执行的处理包前包后不一致 等待验证 现按照前后均包处理*/
                .where(ActionBeanDao.Properties.StartTime.between(startTime, endTime))
                .list();
    }

    /**
     * 获取action存储的数量
     * @return
     */
    public long getActionCount (){
        return this.daoSession.getActionBeanDao().count();
    }

    /**
     * 查询所有的action数据
     * @return 返回actions集合
     */
    public List<ActionBean> selectAllActions () {
        return this.daoSession.getActionBeanDao().queryBuilder().list();
    }

    /**
     * 删除所有的action
     */
    public void deleteAllActions (){
        this.daoSession.getActionBeanDao().deleteAll();
    }
}
